package servlet.upload;

import dao.upload.AccessoryDao;
import entity.upload.EntityAccessory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 下载文件控制器
 *
 * @author xusucheng
 * @create 2017-12-30
 **/
@WebServlet("/downloadUploadedFile")
public class DownloadUploadedFileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //拿到文件ID
        int fileId = Integer.valueOf(request.getParameter("id"));
        EntityAccessory entity = AccessoryDao.load(fileId);
        String filePath = entity.getFilePath();
        String fileName = entity.getFileName();
        String errorMessage = "";
        //判断文件是否存在
        File file = new File(filePath);
        if (file.exists()) {
            //设置响应头
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //创建文件输入流
            FileInputStream is = new FileInputStream(filePath);
            //创建输出流
            OutputStream os = response.getOutputStream();
            //创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            //写数据到浏览器
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            //关闭流
            is.close();
            os.close();
        } else {
            errorMessage = "下载失败，文件：" + filePath + " 不存在";
            request.setAttribute("errorMessage", errorMessage);
            request.getRequestDispatcher("pages/upload/error.jsp").forward(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
